//
//  ACAnchorViewController+LiveDelegate.m
//  ACLiteAVUISDK
//
//  Created by 冯琰琰 on 2021/4/7.
//

#import "ACAnchorViewController+LiveDelegate.h"
#import <SVProgressHUD.h>

@implementation ACAnchorViewController (LiveDelegate)

#pragma mark - LiveRoom
- (void)loginWithRoomID:(NSString *)roomID isAnchor:(BOOL)isAnchor isOwner:(BOOL)isOwner callback:(Callback)callback {
    self.liveRoom = [TRTCLiveRoom shareInstance];
    self.liveRoom.delegate = self;
    self.isAnchor = isAnchor;
    
    self.liveID = roomID;
   
    self.isMC = isOwner;
    
    [self requestLiveInfo];
    
    self.me = [[TRTCLiveUserInfo alloc] init];
    self.me.userId = [ACUserProfileManager shareInstance].userModel.user_id;
    self.me.userName = [ACUserProfileManager shareInstance].userModel.nickname;
    self.me.avatarURL = [ACUserProfileManager shareInstance].userModel.avatar;
    self.me.isOwner = isOwner;
    
    TRTCLiveRoomConfig *config = [[TRTCLiveRoomConfig alloc] init];
    config.useCDNFirst = NO;

    NSString *userSig = [[ACUserProfileManager shareInstance] getUserSig];
   
    dispatch_queue_t queue = dispatch_queue_create("liveRoom", 0);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_async(queue, ^{
        [self.liveRoom loginWithSdkAppID:ACSDKAPPID user:self.me userSig:userSig config:config callback:^(int code, NSString * _Nullable message) {
            if (code == 0) {
                dispatch_semaphore_signal(semaphore);
            }
        }];
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        [self.liveRoom enterRoomWithRoomID:[roomID intValue] isAudience:NO callback:^(int code, NSString * _Nullable message) {
            if (code == 0 || [message isEqualToString:@"当前在房间中"]) {
                DDLogInfo(@"成功进入房间------%@",roomID);
                dispatch_semaphore_signal(semaphore);
            }
        }];
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        @weakify(self)
        if (isOwner) {
            [self.liveRoom startPublishWithStreamID:@"" callback:^(int code, NSString * _Nullable message) {
                @strongify(self)
                if (code == 0) {
                    DDLogInfo(@"成功进入房间------%@-----并开始推流",roomID);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.liveRoom startCameraPreviewWithFrontCamera:YES view:self.videoView callback:^(int code, NSString * _Nullable message) {
                            if (code == 0) {
                                [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
                            }
                        }];
                    });
                }
            }];
        }else{
            [self.liveRoom anchorStartPublishcallback:^(int code, NSString * _Nullable message) {
                @strongify(self)
                if (code == 0) {
                    DDLogInfo(@"主讲成功进入房间------%@-----并开始推流",roomID);
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.liveRoom startCameraPreviewWithFrontCamera:YES view:self.videoView callback:^(int code, NSString * _Nullable message) {
                            if (code == 0) {
                                [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
                            }
                        }];
                    });
                }
            }];
        }
    });
}
#pragma mark -- TRTCLiveRoomDelegate
-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onRoomInfoChange:(TRTCLiveRoomInfo *)info{
    
}
-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onAudienceEnter:(TRTCLiveUserInfo *)user{
    
}
-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onAudienceExit:(TRTCLiveUserInfo *)user{
    
}
-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onAnchorEnter:(NSString *)userID{
    //  普通观众 渲染 主播视频
    dispatch_async(dispatch_get_main_queue(), ^{
        if (userID == self.me.userId) {

        }else{
            if ([userID startsWith:@"tic_push_user"] ) { // 且不是我自己在共享
                NSArray *array = [userID componentsSeparatedByString:@"_"];
                if (![array containsObject:self.me.userId]) {
                    // 显示白板
                    [self showWriteBoardViewWithuserID:userID];
                }else if (![array containsObject:self.me.userId]){
                    // 本人在推白板的流，打开工具条
                    
                }
            }else{
                [trtcLiveRoom startPlayWithUserID:userID view:self.videoView callback:^(int code, NSString * _Nullable message) {
                
                }];
            }
        }
    });
}
-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onAnchorExit:(NSString *)userID{
    //  普通观众 移除 主播视频
    if (userID == self.me.userId) {
        [trtcLiveRoom stopCameraPreview];
    }else{
        if ([userID startsWith:@"tic_push_user"] ) { // 且不是我自己在共享
            NSArray *array = [userID componentsSeparatedByString:@"_"];
            if (![array containsObject:self.me.userId]) {
                // 移除白板View
                [self removeWriteBoardViewWithuserID:userID];
            }
        }else{
            [trtcLiveRoom stopPlayWithUserID:userID callback:^(int code, NSString * _Nullable message) {
                
            }];
        }
    }
}
-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onChangeRequestJoinAnchorList:(NSArray<TRTCLiveUserInfo *> *)requestJoinAnchor{
    DDLogInfo(@"---------%@",requestJoinAnchor);
}
-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onRequestJoinAnchor:(TRTCLiveUserInfo *)user reason:(NSString *)reason timeout:(double)timeout{
    // 更新人员到 请求上麦列表中
    [self.requestJoinAnchorArray addObject:user];
}

-(void)trtcLiveRoomOnQuitJoinAnchor:(TRTCLiveRoom *)liveRoom leaveUser:(nonnull TRTCLiveUserInfo *)user{
    [SVProgressHUD showSuccessWithStatus:@"你好，收到了连麦观众主动退出的消息"];
    // 将麦上观众移除
    [self.requestJoinAnchorArray removeObject:user];
}

-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom OnResponseInviteAnchor:(TRTCLiveUserInfo *)user agreed:(BOOL)agreed{
    DDLogInfo(@"--------%@-------------你好，收到了主讲人邀请的应答",NSStringFromSelector(@selector(trtcLiveRoom:OnResponseInviteAnchor:agreed:)));
    [self receiveInviteAnchorResponseWithInviteAnchor:user agreed:agreed];
    
}


-(void)trtcLiveRoomOnQuitInviteAnchor:(TRTCLiveRoom *)trtcLiveRoom{
    DDLogInfo(@"--------%@-------------你好，收到了主讲主动退出的消息",NSStringFromSelector(@selector(trtcLiveRoomOnQuitInviteAnchor:)));
    [self receiveInviteAnchorLeave];
}

-(void)trtcLiveRoomOnKickoutInviteAnchor:(TRTCLiveRoom *)trtcLiveRoom{
    DDLogInfo(@"--------%@-------------你好，主讲你被主持人踢出了",NSStringFromSelector(@selector(trtcLiveRoomOnKickoutInviteAnchor:)));
    [self receiveInviteAnchorKickedOut];
}

-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom feedInfo:(TRTCLiveRoomFeedbackInfoType)feedInfo{
    
}
// 收到文本消息 展示
- (void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onRecvRoomTextMsg:(NSString *)message fromUser:(TRTCLiveUserInfo *)user{
    ACMsgModel *msgModel = [[ACMsgModel alloc] init];
    msgModel.userName = user.userName;
    msgModel.userId = user.userId;
    msgModel.userHeadImageUrl = user.avatarURL;
    msgModel.userMsg = message;
    [self bulletNewMsg:msgModel];
}
-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onRecvRoomCustomMsgWithCommand:(NSString *)command message:(NSString *)message fromUser:(TRTCLiveUserInfo *)user{
    
}

-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onRoomDestroy:(NSString *)roomID{
    
}
-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onWarning:(NSInteger)code message:(NSString *)message{
    
}
- (void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onError:(NSInteger)code message:(NSString *)message{
    
}

-(void)trtcLiveRoom:(TRTCLiveRoom *)trtcLiveRoom onTEBHistroyDataSyncCompleted:(UIView *)renderView{
    [self showWriteBoardViewWithBoardView:renderView];
}
@end
